<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #billTypeSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择单据类型" @search="billTypeOpen" />
      </template>
      <template #currencySlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择币种" @search="open" />
      </template>
      <template #supplierSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择供应商" @search="openSupplier" />
      </template>
      <template #taxPortfolioSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择税组合" @search="openTaxPortfolio" />
      </template>
      <template #receivingPrincipleSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择出货原则" @search="openPaymentCondition(3)" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="委外收货单子表" key="busOutsourcingPurchaseReturnItemList" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busPurchaseReceiveItem"
          :loading="busPurchaseReceiveItemTable.loading"
          :columns="busPurchaseReceiveItemTable.columns"
          :dataSource="busPurchaseReceiveItemTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
          @valueChange="valueChange"
        >
          <template #action="props">
            <a-input-search @search="handleView(props)" placeholder="请选择料品编码" v-model:value="props.row.materialCode"></a-input-search>
          </template>
          <template #warehouse="props">
            <a-input-search @search="handleWarehouseView(props)" placeholder="请选择仓库" v-model:value="props.row.storageLocation"></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"></billTypeSelectModel>
  <!-- 币种 -->
  <currencySelectModel @register="regModal" @getSelectResult="handleSuccess" v-bind="getBindValue"></currencySelectModel>
  <!-- 供应商 -->
  <supplierSelectModel @register="supplierRegModal" @getSelectResult="supplierHandleSuccess" v-bind="getBindValue"></supplierSelectModel>
  <!-- 税额 -->
  <taxSelectModel @register="taxRegModal" @getSelectResult="taxHandleSuccess" v-bind="getBindValue"></taxSelectModel>
  <!-- 条件 -->
  <paymentConditionSelectModel
    @register="paymentConditionRegModal"
    @getSelectResult="paymentConditionHandleSuccess"
    v-bind="getBindValue"
  ></paymentConditionSelectModel>
  <!-- 料品 -->
  <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"></materialSelectModel>
  <!-- 仓库 -->
  <warehouseSelectModel @register="warehouseRegModal" @getSelectResult="warehousehandleSuccess" v-bind="getBindValue"></warehouseSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { useCountTax } from '/@/hooks/system/useCountTax.ts';
import { formSchema, busPurchaseReceiveItemColumns } from '../BusOutsourcingPurchaseReturn.data';
import { saveOrUpdate, busPurchaseReceiveItemList, taxList, saveOrUpdateItem } from '../BusOutsourcingPurchaseReturn.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import currencySelectModel from './currencySelectModel.vue';
import supplierSelectModel from './supplierSelectModel.vue';
import taxSelectModel from '/@/views/components/taxSelectModel.vue';
import paymentConditionSelectModel from './paymentConditionSelectModel.vue';
import materialSelectModel from './materialSelectModel.vue';
import warehouseSelectModel from '/@/views/components/warehouseSelectModel.vue';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const formDisabled = ref(false);
const refKeys = ref(['busPurchaseReceiveItem']);
const activeKey = ref('busPurchaseReceiveItem');
const busPurchaseReceiveItem = ref();
const tableRefs = { busPurchaseReceiveItem };
const busPurchaseReceiveItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: busPurchaseReceiveItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busPurchaseReceiveItemList, { purchaseOrderId: data?.record?.id }, busPurchaseReceiveItemTable);
  } else {
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busOutsourcingPurchaseReturnItemList';
  busPurchaseReceiveItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busOutsourcingPurchaseReturnItemList: allValues.tablesValue[0].tableData,
  };
}

//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
let arr1: number = 0;
let arr2: number = 0;
let capacity: number = 0;
let num1: number = 0;
let num2: number = 0;
//税额计算
// const {sumTotalValueTax, sumTax, sumAmountNotTaxed }= useCountTax();
//计算税额
function valueChange(e) {
  //采购数量
  if (e.col.key == 'purchaseQuantity') {
    let arr: any = [];
    arr = e.value.toString().split('.');
    if (arr[1]) {
      //num=arr[0]*(10**arr[1].length)
      arr1 = arr[1].length;
      num1 = arr[0].toString() + arr[1].toString();
    }
  }
  if (e.col.key == 'purchasePrice') {
    let arr: any = [];
    arr = e.value.toString().split('.');
    if (arr[1]) {
      //num=arr[0]*(10**arr[1].length)
      arr2 = arr[1].length;
      num2 = arr[0].toString() + arr[1].toString();
    }
  }

  capacity = arr1 > arr2 ? arr1 : arr2 > arr1 ? arr2 : arr2 == arr1 ? arr2 : 1;
  capacity = 10 ** capacity;
  let taxRate = getFieldsValue().taxRate ? Number(getFieldsValue().taxRate) / 100 : 0;
  let obj = {
    whetherTax: getFieldsValue().whetherTax,
    taxRate: taxRate,
    capacity: capacity,
    purchasePrice: e.row.purchasePrice,
    purchaseQuantity: e.row.purchaseQuantity,
  };
  if (Number(num1) && Number(num2)) {
    console.log(obj)
    // // //价税合计
    // e.row.sumTotalValueTax = sumTotalValueTax(obj);
    // // 税额
    // e.row.tax = sumTax(obj);
    // // 未税金额
    // e.row.amountNotTaxed = sumAmountNotTaxed(obj);
    if (getFieldsValue().whetherTax == 1) {
      //价税合计 = 数量* 销售单价
      e.row.totalValueTax = ((e.row.purchaseQuantity * capacity * (e.row.purchasePrice * capacity)) / (capacity * capacity)).toFixed(2);
      // 税额 = 价税合计 /(1 + 税率) * 税率
      e.row.tax = ((e.row.totalValueTax / (1 + taxRate)) * taxRate).toFixed(2);
      // 未税金额 = 价税合计 - 税额
      e.row.amountNotTaxed = (e.row.totalValueTax - e.row.tax).toFixed(2);
    } else {
      //未税金额 = 数量* 销售单价
      e.row.amountNotTaxed = ((e.row.purchaseQuantity * capacity * (e.row.purchasePrice * capacity)) / (capacity * capacity)).toFixed(2);
      // 税额 = 未税金额 /(1 + 税率) * 税率
      e.row.tax = ((e.row.amountNotTaxed / (1 + taxRate)) * taxRate).toFixed(2);
      //价税合计 = 未税金额+ 税额
      e.row.totalValueTax = Number(e.row.amountNotTaxed)+ Number(e.row.tax)
    }
  } else {
    if (getFieldsValue().whetherTax == 1) {
      //价税合计 = 数量* 销售单价
      e.row.totalValueTax = (e.row.purchaseQuantity * e.row.purchasePrice).toFixed(2);
      // 税额 = 价税合计 /(1 + 税率) * 税率
      e.row.tax = ((e.row.totalValueTax / (1 + taxRate)) * taxRate).toFixed(2);
      // 未税金额 = 价税合计 - 税额
      e.row.amountNotTaxed = (e.row.totalValueTax - e.row.tax).toFixed(2);
    } else {
      //未税金额 = 数量* 销售单价
      e.row.amountNotTaxed = (e.row.purchaseQuantity * e.row.purchasePrice).toFixed(2);
      // 税额 = 未税金额 /(1 + 税率) * 税率
      e.row.tax = ((e.row.amountNotTaxed / (1 + taxRate)) * taxRate).toFixed(2);
      //价税合计 = 未税金额+ 税额
      e.row.totalValueTax = Number(e.row.amountNotTaxed)+ Number(e.row.tax)
    }
  }
  console.log(e);
}
const [regModal, { openModal }] = useModal();
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
const [supplierRegModal, { openModal: supplierModal }] = useModal();
const [taxRegModal, { openModal: taxModal }] = useModal();
const [paymentConditionRegModal, { openModal: openPaymentConditionModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [warehouseRegModal, { openModal: openWarehouseModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();

const getBindValue = Object.assign({}, '');

//单据类型
function billTypeOpen() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择币种
function open() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择供应商
function openSupplier() {
  supplierModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择税组合
function openTaxPortfolio() {
  taxModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

//打开选择条件
function openPaymentCondition(type) {
  openPaymentConditionModal(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}
let index: number | null = null;
//打开选择料品
function handleView(props) {
  index = props.params.$rowIndex;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开仓库
function handleWarehouseView(props) {
  index = props.params.$rowIndex;
  openWarehouseModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开单位选择
function handleUnitView(props) {
  index = props.params.$rowIndex;
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//币种选择回写
function handleSuccess(val, values) {
  setFieldsValue({
    currencyName: val[0].label,
    currencyId: val[0].value,
  });
}
//单据类型回写
function billTypehandleSuccess(val, values) {
  setFieldsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
  });
}
//供应商回写
function supplierHandleSuccess(val, values) {
  setFieldsValue({
    supplierName: val[0].label,
    supplierId: val[0].value,
  });
}
//税额回写
function taxHandleSuccess(val, values) {
  setFieldsValue({
    taxPortfolio: val[0].label,
    taxPortfolioId: val[0].value,
    taxRate: val[0].labels,
  });
}
//条件选择回写
function paymentConditionHandleSuccess(val, values, type) {
  if (type == 3) {
    setFieldsValue({
      receivingPrinciple: val[0].label,
      receiptPrincipleId: val[0].value,
    });
  }
}
//料品回写
function materialhandleSuccess(val, values) {
  busPurchaseReceiveItemTable.dataSource = busPurchaseReceiveItem.value!.getTableData();
  busPurchaseReceiveItemTable.dataSource[index].materialName = val[0].label;
  busPurchaseReceiveItemTable.dataSource[index].materialId = val[0].value;
  busPurchaseReceiveItemTable.dataSource[index].materialCode = val[0].item.code;
  busPurchaseReceiveItemTable.dataSource[index].specifications = val[0].item.spec;
  
  // 自动带出单位
  busPurchaseReceiveItemTable.dataSource[index].unitId = val[0].item.stockUnitId;
  busPurchaseReceiveItemTable.dataSource[index].unitName = val[0].item.stockUnitName;

}
//仓库回写
function warehousehandleSuccess(val, values) {
  busPurchaseReceiveItemTable.dataSource = busPurchaseReceiveItem.value!.getTableData();
  busPurchaseReceiveItemTable.dataSource[index].storageLocation = val[0].label;
  busPurchaseReceiveItemTable.dataSource[index].storageLocationId = val[0].value;
}
//单位回写
function unithandleSuccess(val, values) {
  busPurchaseReceiveItemTable.dataSource = busPurchaseReceiveItem.value!.getTableData();
  busPurchaseReceiveItemTable.dataSource[index].unitName = val[0].label;
  busPurchaseReceiveItemTable.dataSource[index].unitId = val[0].value;
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>